package com.microservice.skeleton.upms.constraints;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.metadata.BeanDescriptor;
import javax.validation.metadata.ConstraintDescriptor;
import javax.validation.metadata.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: lijin
 * @date: 2018年11月07日
 */
public class ValidatorConstraintResolver implements ConstraintResolver {

    private final Validator validator;

    /**
     * Creates a new {@code ValidatorConstraintResolver} that will use a {@link Validator}
     * in its default configuration to resolve constraints.
     *
     * @see Validation#buildDefaultValidatorFactory()
     * @see ValidatorFactory#getValidator()
     */
    public ValidatorConstraintResolver() {
        this(Validation.buildDefaultValidatorFactory().getValidator());
    }

    /**
     * Creates a new {@code ValidatorConstraintResolver} that will use the given
     * {@code Validator} to resolve constraints.
     *
     * @param validator the validator
     */
    public ValidatorConstraintResolver(Validator validator) {
        this.validator = validator;
    }

    @Override
    public List<Constraint> resolveForProperty(String property, Class<?> clazz) {
        List<Constraint> constraints = new ArrayList<>();
        BeanDescriptor beanDescriptor = this.validator.getConstraintsForClass(clazz);
        PropertyDescriptor propertyDescriptor = beanDescriptor
                .getConstraintsForProperty(property);
        if (propertyDescriptor != null) {
            for (ConstraintDescriptor<?> constraintDescriptor : propertyDescriptor
                    .getConstraintDescriptors()) {
                constraints.add(new Constraint(
                        constraintDescriptor.getAnnotation().annotationType().getName(),
                        constraintDescriptor.getAttributes()));
            }
        }
        return constraints;
    }

}
